package cn.lcl.factory;

import cn.lcl.dao.BaseDao;
import cn.lcl.util.ProUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * dao实例建造工厂
 * Created by licho on 2017/8/15 0015.
 */
public class DaoFactory{
    private static  final Map<Class<? extends BaseDao>,Object> bean=new HashMap<>();//存放dao bean实例
    public static <T extends BaseDao>  T getDaoInstance(Class<T> dao){
        String className=dao.getName();//获取完整类的限定
        System.out.println("dao"+dao.getSimpleName()+"is exist:"+bean.containsKey(dao));
        if(!bean.containsKey(dao)){
            //说明不包含该对象
            synchronized (bean){
                if(bean.containsKey(dao))
                    return dao.cast(bean.get(dao));
                String implName=ProUtils.getProperty(className);//找到配置的具体实现类
                System.out.println(implName);
                try {
                    Class<?> type=Class.forName(implName);
                    Constructor<?> constructor = type.getConstructor();//获取默认构造方法
                    Object obj=constructor.newInstance();//创建dao实现类对象
                    bean.put(dao,obj);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        Object obj=bean.get(dao);
        return dao.cast(obj);

    }
}
